package com.zbkj.common.core;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.Img;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.tiangong.framework.bo.CDO;
import com.tiangong.framework.bo.Return;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

public class FilesUtil {
    private static  String accessKeyId="LTAI5tKSTGYtzCAegWEPsfwW";
    private static  String accessKeySecret="3eaep1dqzxG9LIGujCuo29fqIW1dkn";
    private static  String domain="https://zimijob.oss-cn-beijing.aliyuncs.com";
    private static  String bucket="zimijob";
    private static  String endpoint = "https://oss-cn-beijing.aliyuncs.com";

    public static Return upload(MultipartFile mfile, Boolean compress) {


        long size = mfile.getSize()/1024;
        if(size<=300){
            compress=false;
        }
//        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

//        MultipartFile mfile = multipartRequest.getFile("file");// 获取上传文件对象

        String contentType1 = mfile.getContentType();
        String [] fileInfo = mfile.getOriginalFilename().split("\\.");
        String fileFormat = fileInfo[fileInfo.length - 1];
        String fileSourceName = fileInfo[fileInfo.length - 2];
        String name=UUID.randomUUID()+ RandomStringUtils.random(4, false, true);
        String fileName = name + "." + fileFormat;

        InputStream fileInputStream_old = null;
        try {
            fileInputStream_old = mfile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //WARN
     //   FileUtil.re


        //InputStream fileInputStream = null;
        File newFile=new File(fileName);
        try {
            if(compress!=null&&compress){
                fileName=name+".jpg";
                Img.from(fileInputStream_old).setQuality(0.3).write(newFile);
              //  fileInputStream=new FileInputStream(newFile);
            }
//            else {
//                fileInputStream=fileInputStream_old;
//            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        ObjectMetadata metadata = new ObjectMetadata();
        long length = newFile.length();
        //上传的文件的长度
        try {
            metadata.setContentLength(newFile.length()==0?fileInputStream_old.available():newFile.length());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //指定该Object被下载时的网页的缓存行为
        metadata.setCacheControl("no-cache");
        //指定该Object下设置Header
        metadata.setHeader("Pragma", "no-cache");
        //指定该Object被下载时的内容编码格式
        metadata.setContentEncoding("utf-8");
        //文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
        //如果没有扩展名则填默认值application/octet-stream
        String contentType = getContentType(fileName);
        if(StringUtils.isNotBlank(contentType)){
            metadata.setContentType(contentType);
        }
        //指定该Object被下载时的名称（指示MINME用户代理如何显示附加的文件，打开或下载，及文件名称）
        metadata.setContentDisposition("filename/filesize=" + fileName + "/"  + "Byte.");

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String dirName = "img"+"/"+System.currentTimeMillis();

        if(contentType.contains("image")){
            dirName="static/image/"+DateUtil.format(DateUtil.date(),"yyyyMMdd");
        }else {
            dirName="static/files/"+DateUtil.format(DateUtil.date(),"yyyyMMdd");
        }

        try {
            if(newFile.length()!=0){
                PutObjectResult putObjectResult = ossClient.putObject(bucket, dirName+"/"+fileName , newFile,metadata);
                size=newFile.length()/1024;
            }else {
                PutObjectResult putObjectResult = ossClient.putObject(bucket, dirName+"/"+fileName , fileInputStream_old,metadata);
            }
        } catch (Exception oe) {
           oe.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        String url=domain+"/"+dirName+"/"+fileName;
        System.out.println(url);
        CDO cdoResult=new CDO();
        cdoResult.set("url",url);
        cdoResult.set("filesize",size);
        cdoResult.set("compress",newFile.length()!=0?true:false);
        if(newFile.exists()){
            newFile.delete();
        }
        return Return.valueOf(cdoResult);
    }
    public static String upload1(MultipartFile mfile) {
//        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

//        MultipartFile mfile = multipartRequest.getFile("file");// 获取上传文件对象
        String [] fileInfo = mfile.getOriginalFilename().split("\\.");
        String fileFormat = fileInfo[fileInfo.length - 1];
        String fileSourceName = fileInfo[fileInfo.length - 2];
        String fileName = fileSourceName + "." + fileFormat;

        InputStream fileInputStream = null;
        try {
            fileInputStream = mfile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ObjectMetadata metadata = new ObjectMetadata();
        //上传的文件的长度
        try {
            metadata.setContentLength(fileInputStream.available());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //指定该Object被下载时的网页的缓存行为
        metadata.setCacheControl("no-cache");
        //指定该Object下设置Header
        metadata.setHeader("Pragma", "no-cache");
        //指定该Object被下载时的内容编码格式
        metadata.setContentEncoding("utf-8");
        //文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
        //如果没有扩展名则填默认值application/octet-stream
        String contentType = getContentType(fileName);
        if(StringUtils.isNotBlank(contentType)){
            metadata.setContentType(contentType);
        }
        //指定该Object被下载时的名称（指示MINME用户代理如何显示附加的文件，打开或下载，及文件名称）
        metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileInputStream + "Byte.");

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String dirName = "img"+"/"+System.currentTimeMillis();
        if(contentType.contains("image")){
            dirName="image/"+System.currentTimeMillis();
        }else {
            dirName="files/"+System.currentTimeMillis();
        }

        try {
            PutObjectResult putObjectResult = ossClient.putObject(bucket, dirName+"/"+fileName , fileInputStream,metadata);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        String url=domain+"/"+dirName+"/"+fileName;
        System.out.println(url);
        return url;
    }

    /**
     * 通过文件名判断并获取OSS服务文件上传时文件的contentType
     *
     * @param fileName 文件名
     * @return 文件的contentType
     */
    public  static  String getContentType(String fileName) {
        //文件的后缀名
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        if (".bmp".equalsIgnoreCase(fileExtension)) {
            return "image/bmp";
        }
        if (".gif".equalsIgnoreCase(fileExtension)) {
            return "image/gif";
        }
        if (".jpeg".equalsIgnoreCase(fileExtension)
                || ".jpg".equalsIgnoreCase(fileExtension) ||
                ".png".equalsIgnoreCase(fileExtension)) {
            return "image/jpeg";
        }
        if (".html".equalsIgnoreCase(fileExtension)) {
            return "text/html";
        }
        if (".txt".equalsIgnoreCase(fileExtension)) {
            return "text/plain";
        }
        if (".vsd".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.visio";
        }
        if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
            return "application/msword";
        }
        if (".xml".equalsIgnoreCase(fileExtension)) {
            return "text/xml";
        }
        if (".flv".equalsIgnoreCase(fileExtension)) {
            return "video/x-flv";
        }
        if (".mp3".equalsIgnoreCase(fileExtension)) {
            return "audio/mpeg";
        }
        if (".mp4".equalsIgnoreCase(fileExtension)) {
            return "video/mp4";
        }
        //默认返回类型
        return "";
    }

    public static void main(String[] args) throws Exception {
        System.out.println(DateUtil.format(DateUtil.date(),"yyyyMMdd"));
    }
}
